import { getDateNow, getValidDate } from '@/dataTransfer/coupon';
import { transformConfig } from '@/utils/customModule';
import { keyBy } from '@/utils/fn';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { defaultVisibleEnums } from '../../moduleConstants';
import ActivityHeader from '../ActivityHeader';
import {
  LimitDiscountsBorderRadius,
  LimitDiscountsGoodsStyle,
  LimitDiscountsSelectType,
  LimitDiscountStyle,
} from './constants';
import HorizontalProducts from './HorizontalProducts';
import styles from './index.module.scss';
import VerticalProducts from './VerticalProducts';

const styleConfig = {
  wrap: (styleSettingRender) => {
    if (styleSettingRender?.opacity === defaultVisibleEnums.show) {
      return { backgroundColor: 'white' };
    }
  },
};

const ModuleOffActivity = ({
  dispatch,
  loading,

  componentCfg: { styleSettingRender = {}, content = {} } = {},
}) => {
  useShowLoading(loading, ['productList/fetchActivityProductList']);

  const style = useMemo(() => {
    return transformConfig(styleSettingRender, styleConfig, content);
  }, [styleSettingRender, styleConfig, content]);

  // 设置活动列表
  const [activityList, setActivityList] = useState([]);
  // 设置选中活动
  const [activity, setActivity] = useState();
  // 当前活动商品列表
  const [products, setProducts] = useState([]);

  const {
    items,

    showCart,
    cartStyle,
    showSoldOut,
    showCountdown,
    showSalePrice,
    activityPosition,
    showGoodsSaleNum,
  } = content;

  // 获取活动列表
  useEffect(() => {
    dispatch({
      type: 'giftCard/fetchModuleActivityList',
      payload: {
        activityIds: items?.map(({ activityId }) => {
          return activityId;
        }),
        page: 1,
        pageSize: items?.length,
      },
    })
      .then((list) => {
        const o = keyBy(list, 'id');

        return items.map(({ activityId, ...rest }) => {
          return {
            startTime: 0,
            endTime: 0,
            ...o[activityId],
            activityId,
            ...rest,
          };
        });
      })
      .then((list) => {
        setActivityList(list);
      });
  }, [items]);

  // 设置默认选中活动
  useEffect(() => {
    setActivity(activityList?.[0]);
  }, [activityList]);

  // 获取活动商品
  useEffect(() => {
    if (!activity) {
      return;
    }

    if (getDateNow() >= getValidDate(activity.endTime).getTime()) {
      setProducts([]);
      return;
    }

    dispatch({
      type: 'productList/fetchActivityProductList',
      payload: {
        activityId: activity.activityId,
        ids:
          activity.selectType === LimitDiscountsSelectType.auto
            ? undefined
            : activity.goodsList.map(({ id }) => {
                return id;
              }),
        shelvesFlagType: 2,
        page: 1,
        pageSize:
          activity.selectType === LimitDiscountsSelectType.auto
            ? activity.goodsCount
            : activity.goodsList?.length,
      },
    }).then((list) => {
      setProducts(list);
    });
  }, [activity]);

  const productListProps = {
    activity,
    products,

    isShowSalePrice: showSalePrice === defaultVisibleEnums.show,
    isShowSoldOut: showSoldOut === defaultVisibleEnums.show,

    isShowGoodsSaleNum: showGoodsSaleNum === defaultVisibleEnums.show,

    isShowCart: showCart === defaultVisibleEnums.show,

    // 是否开始活动
    isStart: activity?.startTime ? Date.now() >= getValidDate(activity?.startTime) : false,

    cartStyle,
    activityPosition,
  };

  return (
    <View className={styles.ModuleOffActivity} style={{ ...style.module, ...style.wrap }}>
      <View
        className={classNames('activity-detail', {
          'activity-card': styleSettingRender.goodsStyle === LimitDiscountsGoodsStyle.card,
          border: styleSettingRender.goodsStyle === LimitDiscountsGoodsStyle.border,
          radius: styleSettingRender.borderType === LimitDiscountsBorderRadius.circle,
        })}
      >
        <ActivityHeader
          {...{
            activityList,
            value: activity,
            onChange: setActivity,

            isShowCountdown: showCountdown === defaultVisibleEnums.show,
          }}
        />

        {styleSettingRender?.style === LimitDiscountStyle.one && (
          <VerticalProducts {...productListProps} />
        )}

        {styleSettingRender?.style === LimitDiscountStyle.two && (
          <HorizontalProducts {...productListProps} />
        )}
      </View>
    </View>
  );
};

export default connect(({ loading }) => ({
  loading,
}))(ModuleOffActivity);
